﻿#include "DSystemTrayMenu.h"
#include "HDQt/HDQt.hpp"
#include "hook.h"
#include "OneKeyboard.h"
#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QIcon>
#include <QMessageBox>
#include <QProcess>
#include <QSettings>
#include <QSystemTrayIcon>


int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
    OneKeyboard w;

	QSystemTrayIcon trayIcon(QIcon(":icon.ico"));
	trayIcon.setToolTip("OneKeyboard");
	QObject::connect(&trayIcon, &QSystemTrayIcon::activated, &w, [&w](QSystemTrayIcon::ActivationReason reason)
	{
		switch (reason)
		{
		case QSystemTrayIcon::Unknown:
			break;
		case QSystemTrayIcon::Context:
			break;
		case QSystemTrayIcon::DoubleClick:
			break;
		case QSystemTrayIcon::Trigger:
			w.show();
			w.activateWindow();
			break;
		case QSystemTrayIcon::MiddleClick:
			break;
		default:
			break;
		}
	});

	// 任务栏图标右键菜单
	const static DList<TrayItemInfo> infos = { TrayItemInfo(QObject::tr("打开")), TrayItemInfo(QObject::tr("还原鼠标")), TrayItemInfo(QObject::tr("还原键盘")), TrayItemInfo(QObject::tr("开机启动"), true), TrayItemInfo(QObject::tr("退出")) };
	DSystemTrayMenu trayMenu(infos);
	
	// 设置开机启动按钮是否勾选
	QString applicationName = QApplication::applicationName();  // 获取应用名称
	QString applicationPath = QApplication::applicationFilePath();  // 找到应用的目录
	trayMenu.actionAt(3)->setChecked(HDQt::getExeStartByPC(applicationName, applicationPath));

	QObject::connect(&trayMenu, &DSystemTrayMenu::sigItemClicked, [&w](QAction* action)
	{
		QString text = action->text();
		switch (infos.indexOf(text))
		{
		case 0:  // 打开
			w.show();
			w.activateWindow();
			break;
		case 1:  // 还原鼠标
			w.on_btn_reset_mouse_clicked();
			break;
		case 2:  // 还原键盘
			w.on_btn_reset_key_clicked();
			break;
		case 3:  // 开机启动
		{
			bool startByPC = action->isChecked();
			QString applicationName = QApplication::applicationName();  // 获取应用名称
			QString applicationPath = QApplication::applicationFilePath();  // 找到应用的目录

			QString exePath = QApplication::applicationDirPath() + "/StartByPC.exe";
			if (!QFile::exists(exePath))
			{
				QMessageBox::warning(nullptr, QObject::tr("有些事情好像不太行"), QObject::tr("文件缺失：%1").arg(exePath));
				return;
			}

			QStringList args = { "name=" + applicationName, "path=" + applicationPath, "start=" + QString::number(startByPC) };
			if (!QProcess::startDetached(exePath, args))
				action->setChecked(!startByPC);
			break;
		}
		case 4:  // 关闭
			w.close();
			break;
		}
	});

	trayIcon.setContextMenu(&trayMenu);
	trayIcon.show();

	Hook::getInstance()->installHook();
	QObject::connect(Hook::getInstance(), &Hook::sendKeyType, &w, &OneKeyboard::slotKeyPressed, Qt::QueuedConnection);
	QObject::connect(Hook::getInstance(), &Hook::sendMouseType, &w, &OneKeyboard::slotMousePressed, Qt::QueuedConnection);
	QObject::connect(&a, &QApplication::aboutToQuit, &w, &OneKeyboard::doBeforeExit);
	QObject::connect(&a, &QApplication::aboutToQuit, Hook::getInstance(), &Hook::unInstallHook);

    w.show();
    return a.exec();
}
